/**
 * When this page is accessed, truffles are pushed out to all currently
 * searching devices. This could easily be made more interesting by
 * adding some random or some deterministic element.
 */

package com.bowlofnoodles.truffles;

import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

@SuppressWarnings("serial")
public class TruffleDistribServlet extends HttpServlet {

	Calendar layOff;
	int fallBackSecs = 2; // double this each time we fail

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		resp.setContentType("text/plain");

		resp.getWriter().println("truffle distributor");

		
		// This is if we want only the GAE cron job to be able to hit this page.
		/*
		System.out.println("are you cron?");
		if (req.getHeader("X-AppEngine-Cron") == null) return;
		System.out.println("hi cron!");
		*/

		// don't try if we were told to back off.
		if (layOff != null && !(new GregorianCalendar().after(layOff))) return;

		// get the auth cookie.
		URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
		HTTPRequest auth = new HTTPRequest(new URL("https://www.google.com/accounts/ClientLogin"),HTTPMethod.POST);
		
		// test gmail account for sending - any gmail address signed up for c2dm's credentials can be used here
		String postParams = "accountType=Google&Email=149258@gmail.com&Passwd=852941852941&service=ac2dm&source=trufflesearch";
		auth.setPayload(postParams.getBytes("UTF-8"));
		HTTPResponse response = urlFetchService.fetch(auth);
		String authResponse = new String(response.getContent());
		resp.getWriter().println(authResponse);
		String authCookie = authResponse.substring(authResponse.indexOf("Auth=")+5);
		

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		// get currently searching users.
		Query q = new Query("User");
		q.addFilter("searchingNow", Query.FilterOperator.EQUAL, true);

		TrufflePusher tp = new TrufflePusher(authCookie);
		
		PreparedQuery pq = datastore.prepare(q);

		for (Entity result : pq.asIterable()) {
			
			tp.push(result.getProperty("c2dm_reg_id").toString(), "1", resp);
			
			try {
				int oldGrams = Integer.parseInt(result.getProperty("gramsFound").toString());
				oldGrams++;
				result.setProperty("gramsFound", oldGrams);
			} catch (Exception e) {
				resp.getWriter().println("error in increment grams");
			}
			datastore.put(result);
			
		}
		
	}

}

